from django.contrib import admin
from .models import Procedure, Month, PredictionFact, Event


@admin.register(Procedure)
class ProcedureAdmin(admin.ModelAdmin):
    list_display = ('name', 'specialization', 'price', 'duration', 'min_research_count', 'max_research_count')
    list_editable = ('min_research_count', 'max_research_count')
    list_filter = ('specialization',)
    search_fields = ('name', 'description')
    fieldsets = ((None, {
            'fields': ('name', 'specialization', 'description', 'duration',
                       'min_research_count', 'max_research_count', 'price')
        }),
    )


@admin.register(Month)
class MonthAdmin(admin.ModelAdmin):
    list_display = ('id', 'year', 'month', 'status')
    list_filter = ('year', 'month', 'status')
    search_fields = ('year', 'month', 'status')
    ordering = ('year', 'month', 'status')
    fields = ('year', 'month', 'status')
    actions = ['create_events', 'recreate_events']

    def create_events(self, request, queryset):
        for month in queryset:
            month.create_events()
        self.message_user(request, "Events created successfully.")

    def recreate_events(self, request, queryset):
        for month in queryset:
            month.recreate_events()
        self.message_user(request, "Events recreated successfully.")

    create_events.short_description = "Create Events for selected months"
    recreate_events.short_description = "Recreate Events for selected months"


@admin.register(Event)
class EventAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'month', 'day', 'kind', 'start_time', 'end_time', 'date')
    list_filter = ('month', 'kind', 'user')
    search_fields = ('user__username', 'month__name', 'kind')
    ordering = ('month', 'day', 'start_time')
    fields = ('month', 'day', 'kind', 'user', 'start_time', 'end_time')
    readonly_fields = ('date',)

    def date(self, obj):
        return obj.date.strftime('%Y-%m-%d')

    date.admin_order_field = 'month__year'
    date.short_description = 'Date'


@admin.register(PredictionFact)
class PredictionFactAdmin(admin.ModelAdmin):
    list_display = ('id', 'specialization', 'week', 'qtty', 'qtty_predicted', 'month')
    list_filter = ('specialization', 'week', 'month')
    search_fields = ('specialization__name', 'month__year', 'month__month')
    ordering = ('month', 'week', 'specialization')
    fields = ('specialization', 'week', 'qtty', 'qtty_predicted', 'month')
